//! 全局错误处理的中间件
//! # Example
//! ```
//! use tower::ServiceBuilder;
//! use axum_lib::middleware::error_middleware::ErrorLayer;
//! ServiceBuilder::new()
//!     .layer(ErrorLayer)
//! ```

use crate::middleware::{body_2_string, PinBox};
use crate::{Error};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::{extract::Request, response::Response, };
use log::{error, info};
use std::task::{Context, Poll};
use tower::{Layer, Service};

#[derive(Clone)]
pub struct ErrorLayer;

impl<S> Layer<S> for ErrorLayer {
    type Service = ErrorMiddleware<S>;

    fn layer(&self, inner: S) -> Self::Service {
        ErrorMiddleware { inner }
    }
}

#[derive(Clone)]
pub struct ErrorMiddleware<S> {
    inner: S,
}

impl<S> Service<Request> for ErrorMiddleware<S>
where
    S: Service<Request, Response = Response> + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = PinBox<Self::Response, Self::Error>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request) -> Self::Future {
        let path = request.uri().path();
        info!("访问路径: {path}");
        
        let future = self.inner.call(request);
        Box::pin(async move {
            let response: Response = future.await?;
            let code: StatusCode = response.status();
            if code.is_success() {
                Ok(response)
            }  else {
                let res = body_2_string(response).await;
                if let  Ok(err_msg) = res {
                    error!("错误信息: {err_msg}")
                }
                let msg = super::status_desc(code.as_u16());
                Ok(Error::Business(msg).into_response())
            }
        })
    }
}

